package suery.syntax;

import java.util.Queue;
import java.util.Set;

import suery.ComponentTreeNode;

/**
 * Abstract Search Parser. This class can be used to search from parent nodes,
 * using depth first search.
 * 
 * @author Jeky
 * 
 */
public abstract class AbstractSearchParser implements TokenParser {

    @Override
    public void parse(Queue<String> tokenQueue,
                      Set<ComponentTreeNode> parents,
                      Set<ComponentTreeNode> results) {
        String token = tokenQueue.poll();
        for (ComponentTreeNode p : parents) {
            visit(token, p, results);
        }
    }

    private void visit(String token,
                       ComponentTreeNode node,
                       Set<ComponentTreeNode> results) {
        if (node.getComponent() != null) {
            if (accept(token, node)) {
                results.add(node);
            }
        }

        for (ComponentTreeNode child : node.getChildren()) {
            visit(token, child, results);
        }
    }

    /**
     * Check whether this node is the right one.
     * 
     * @param token token in expression
     * @param node the node of component tree
     * @return if the node is wanted return <b>true</b>, else return
     *         <b>false</b>
     */
    protected abstract boolean accept(String token, ComponentTreeNode node);
}
